package com.bood.shimmer.common.filter;

import com.bood.shimmer.common.annotation.AutoIdempotent;
import com.bood.shimmer.common.service.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * <p>
 * 拦截处理器：主要的功能是拦截扫描到 AutoIdempotent 到注解到方法,然后调用 TokenService 的 checkToken() 方法
 * 校验 token 是否正确，如果捕捉到异常就将异常信息渲染成 json 返回给前端
 * </p>
 *
 * @author：bood
 * @date：2020/9/25
 */
@Component
public class AutoIdempotentInterceptor implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;


    /**
     * <p>
     * 预处理
     * </p>
     *
     * @param request:
     * @param response:
     * @param handler:
     * @return：boolean
     * @author：bood
     * @date：2020/9/23
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 被 @ApiIdempotment 标记的扫描
        AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
        if (methodAnnotation != null) {
            // 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示
            return tokenService.checkToken(request);
        }
        // 必须返回 true,否则会被拦截一切请求
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}